package com.ws.demo1.demos.ConcurrencyBasics;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用ReentrantLock是编程式方式实现。
 */
public class ReentratLockTest extends Thread {

    //计数
    private int count = 0;
    //新建一个ReentrantLock锁对象
    private ReentrantLock reentrantLock = new ReentrantLock();

    public void lockMethod(){
        //先上锁。注意需要与try...finally一起使用
        reentrantLock.lock();
        try{
            //调用count增加方法。
            add();
        } finally {
            //释放锁
            reentrantLock.unlock();
        }

    }

    public synchronized void lockMethod2(){
        add();
    }

    //调用count++方法
    private void add() {
        count++;
        System.out.println(count);
    }

    @Override
    public void run() {
//        lockMethod();
        lockMethod2();
    }

    public static void main(String[] args) {
        ReentratLockTest accountCount = new ReentratLockTest();
        new Thread(accountCount,"A").start();
        new Thread(accountCount,"B").start();
        new Thread(accountCount,"C").start();
        new Thread(accountCount,"D").start();
        new Thread(accountCount,"E").start();
        new Thread(accountCount,"F").start();
    }
    /**
     * 结果：
     * reentrantLock 锁的结果。
     * 1
     * 2
     * 3
     * 4
     * 5
     * 6
     */

    /**
     * synchronized 锁的结果：
     * 1
     * 2
     * 3
     * 4
     * 5
     * 6
     */

}
